package com.haidechizi.i18n.code.generator.common.message.translate.yeecloudmt;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.haidechizi.i18n.code.generator.common.message.translate.mapping.LanguageMappingHolder;
import com.haidechizi.i18n.code.generator.common.message.utils.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author wangdejun
 */
@Slf4j
public class YeeCloudMtUtils {

    public static String translate(String data, String currentLanguage, String language, String appCode) {
        currentLanguage = LanguageMappingHolder.boundingMapping(currentLanguage);
        language = LanguageMappingHolder.boundingMapping(language);
        String host = "http://yeecloudmt.market.alicloudapi.com";
        String path = "/translate";
        String method = "GET";
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", "APPCODE " + appCode);
        Map<String, String> querys = new HashMap<>();
        querys.put("srcl", currentLanguage);
        querys.put("text", data);
        querys.put("tgtl", language);


        try {
            HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
            String result = EntityUtils.toString(response.getEntity());
            if (StringUtils.isNotBlank(result)) {
                JSONObject jsonObject = JSON.parseObject(result, JSONObject.class);
                if ("0".equals(jsonObject.getString("errorCode"))) {
                    return jsonObject.getString("result");
                }
            }
        } catch (Exception e) {
            log.error("翻译失败", e);
        }
        return null;
    }

}
